import { watch, onMounted } from 'vue';

import * as echarts from 'echarts';
import { useVisualizationStore } from '@/stores/visualizationStore';

/**
 * refTarget：
 *  - 传入的Ref, 无需带.value属性(需要在该Hooks->onMounted中调用)
 * renderOption：
 *  - 配置的渲染对象
 */
export default ({ refTarget, renderOptions, openWatch = true }) => {
	// 仓库内容
	const visualizationStore = useVisualizationStore();
	// Echart实例对象
	let chart = {};

	onMounted(() => {
		// 创建Echarts实例
		chart.value = echarts.init(refTarget.value);
		// 配置Echarts
		chart.value.setOption(renderOptions());
	});

	if (openWatch) {
		watch(
			() => visualizationStore.data,
			() => {
				chart.value.setOption(renderOptions());
			}
		);
	}

	// 监视窗口的变化, 让Echart重新自适应容器
	window.addEventListener('resize', () => {
		chart.value.resize();
	});

	return chart;
};
